package com.youxin.cpcenter.service.impl;

import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.youxin.busfoundation.Consts;
import com.youxin.busfoundation.bean.BusinessMessages;
import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.busfoundation.common.redis.RedisOperator;
import com.youxin.busfoundation.config.ZfbBeanConfig;
import com.youxin.busfoundation.enums.EnterpriseIdentityType;
import com.youxin.busfoundation.enums.OrderPayStatusEnums;
import com.youxin.busfoundation.enums.OrderPayTypeEnums;
import com.youxin.busfoundation.enums.PayTypeEnums;
import com.youxin.busfoundation.enums.ProductsCouponEnums;
import com.youxin.busfoundation.enums.SourceTypeEnums;
import com.youxin.cpcenter.bean.RequestOrderInfoBean;
import com.youxin.cpcenter.dao.TbMemberInfoMapper;
import com.youxin.cpcenter.model.TbMemberInfo;
import com.youxin.cpcenter.model.TbOrderInfo;
import com.youxin.cpcenter.service.AliPayService;
import com.youxin.cpcenter.service.TransactionService;
import com.youxin.cpcenter.utils.MemberRightsUtils;
import com.youxin.foundation.db.utils.KeyGenerationUtils;
import com.youxin.foundation.utils.GenerateIdUtils;

import net.sf.json.JSONObject;

/**
 * @ClassName: AliPayServiceImpl
 * @Description: 支付宝业务
 * @author yingde.cao
 * @date 2017年11月24日 下午6:01:02
 */
@Service("aliPayService")
public class AliPayServiceImpl extends BaseServiceImpl implements AliPayService {

	@Autowired
	private TbMemberInfoMapper tbMemberInfoMapper;
	@Autowired
	private TransactionService transactionService;
	private static ZfbBeanConfig zfbBeanConfig = ZfbBeanConfig.getConfig();
	
	@Override
	public ResponseObject aliPayPc(RequestOrderInfoBean requestBean) {
		//是否管理员验证
		//TODO:集成登录权限调整 by jinwen.you
		TbMemberInfo memberInfo = MemberRightsUtils.isAdmin(tbMemberInfoMapper);  
		AlipayClient alipayClient = new DefaultAlipayClient(zfbBeanConfig.getOpenApiDomain(), zfbBeanConfig.getAppid(), zfbBeanConfig.getPrivateKey(), "json", "utf-8", zfbBeanConfig.getAlipayPublicKey(),"RSA2");
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		// 前台通知
		alipayRequest.setReturnUrl(requestBean.getFrontUrl());
		// 后台回调
		alipayRequest.setNotifyUrl(zfbBeanConfig.getNotifyUrl());
		JSONObject bizContent = new JSONObject();
		// 订单号生成
		String orderSn = GenerateIdUtils.getOrderSn();
		bizContent.put("out_trade_no", orderSn);
		String total_amount = "0";
		if(requestBean.getOrderType().equals(OrderPayTypeEnums.VIP.getIndex())){
			total_amount = EnterpriseIdentityType.Vip.getMemberUpgradeFee().toString();
		}else if(requestBean.getOrderType().equals(OrderPayTypeEnums.PTVIP.getIndex())){
			total_amount = EnterpriseIdentityType.Normal.getMemberUpgradeFee().toString();
		}else {
			//total_amount = requestBean.getProductId().toString();
			total_amount = "0.01"; //测试
		}
		bizContent.put("total_amount", total_amount);
		// 订单标题 订单类型 1:充值金券 2:中间号 3:发送短信 4:发送邮件 5:查看联系人 6:商务委托 10:查看微信 11:查看QQ 12:查看固定电话 13:普通会员 14:vip会员
		String subject = OrderPayTypeEnums.getName(requestBean.getOrderType());
		bizContent.put("subject", subject);
		// 实际收款账号，一般填写商户PID即可
		bizContent.put("seller_id", zfbBeanConfig.getPid());
		// 电脑网站支付
		bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
		//bizContent.put("body", subject);
		String biz = bizContent.toString().replaceAll("\"", "'");
		alipayRequest.setBizContent(biz);
		String form = Consts.FAIL_LOWER;
		try {
			form = alipayClient.pageExecute(alipayRequest).getBody();
			requestBean.setPayType(PayTypeEnums.ZFB.getIndex());
			requestBean.setDesc(ProductsCouponEnums.getName(requestBean.getProductId())+"点");
			requestBean.setSource(SourceTypeEnums.Web.getValue());
			transactionService.procesPayTransaction(requestBean, memberInfo, orderSn);
		} catch (AlipayApiException e) {
			return ResponseObject.userFailure("支付宝PC支付下单，构造表单失败" + e);
		}
//		form = form.replaceAll("\\n", "").replaceAll("\"", "");
//		ResponsePayEntranceBean rs = new ResponsePayEntranceBean();
//		rs.setOrderSn(orderSn);
//		rs.setPayEntrance(form);
		long key=KeyGenerationUtils.generateKey();
		RedisOperator.saveAlipay(key,form);
		return new ResponseObject("/ent/alipay/pay/"+key);
	}
	/**
	 * 支付宝回调
	 */
	@Override
	public String aliPayNotify(HttpServletRequest request) {
		String message = Consts.FAIL_LOWER;
		
		TbOrderInfo model = new TbOrderInfo();
		Map<String, String> params = new HashMap<String, String>();
		// 取出所有参数是为了验证签名
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = parameterNames.nextElement();
			params.put(parameterName, request.getParameter(parameterName));
		}

		// 验证签名 校验签名
		boolean signVerified = false;
		try {
			signVerified = AlipaySignature.rsaCheckV1(params, zfbBeanConfig.getAlipayPublicKey(), "UTF-8", "RSA2");
		} catch (AlipayApiException e) {
			model.setPayStatus(OrderPayStatusEnums.PayFaillure.getValue());
			logger.warn("AlipayApiException", e);
		}
		if (signVerified) {
			// 若参数中的appid和填入的appid不相同，则为异常通知
			if (!zfbBeanConfig.getAppid().equals(params.get("app_id"))) {
				model.setPayStatus(OrderPayStatusEnums.PayFaillure.getValue());
				logger.warn("异常通知，订单号："+model.getOrderSn()+",与付款时的appid不同！");
			} else {
				String tradeNo = params.get("trade_no");
				String orderSn = params.get("out_trade_no");
				String totalAmount = params.get("total_amount");
				BigDecimal ta=new BigDecimal(totalAmount);
				model.setPayAmount(ta);
				model.setOrderSn(orderSn);
				String status = params.get("trade_status");
				if (status.equals("WAIT_BUYER_PAY")) { // 如果状态是正在等待用户付款
					model.setPayStatus(OrderPayStatusEnums.UnPay.getValue());
					logger.warn(orderSn + "订单的状态正在等待用户付款");
				} else if (status.equals("TRADE_CLOSED")) { // 如果状态是未付款交易超时关闭，或支付完成后全额退款
					model.setPayStatus(OrderPayStatusEnums.PayClose.getValue());
					logger.warn(orderSn + "订单的状态已经关闭");
				} else if (status.equals("TRADE_SUCCESS") || status.equals("TRADE_FINISHED")) { // 如果状态是已经支付成功
					model.setPayStatus(OrderPayStatusEnums.PaySuccess.getValue());
				} else {
					model.setPayStatus(OrderPayStatusEnums.PayFaillure.getValue());
					logger.warn(orderSn + "未知状态！");
				}
				model.setPlatformNo(tradeNo);
			}
		} else { // 如果验证签名没有通过
			model.setPayStatus(OrderPayStatusEnums.PayFaillure.getValue());
			logger.warn("验证签名失败！");
		}
		//更新订单状态
		String rs = transactionService.procesNotifyTransaction(model);
		if(rs.equals(BusinessMessages.SUCCESS_MESSAGE)) {
			message = Consts.SUCCESS_LOWER;
		}
		return message;
	}

	/*@Override
	public ResponseObject aliPayReturn(HttpServletRequest request) {
		Map<String, String> params = new HashMap<String, String>();
		// 取出所有参数是为了验证签名
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = parameterNames.nextElement();
			params.put(parameterName, request.getParameter(parameterName));
		}
		String orderAmount = params.get("total_amount");
		String payTime = params.get("timestamp");
		String platformNo = params.get("trade_no");
		String orderSn = params.get("out_trade_no");
		BigDecimal ta=new BigDecimal(orderAmount);
		//更新订单状态
		TbOrderInfo model = new TbOrderInfo();
		model.setOrderAmount(ta);
		model.setOrderSn(orderSn);
		model.setPlatformNo(platformNo);
		model.setPayTime(DateUtil.getDateForInt(payTime));
		//更新订单状态
		transactionService.procesNotifyTransaction(model);
		return ResponseObject.successObject(JsonUtils.objectToSfJson(model));
	}*/
}
